package dp.exception;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.mybatis.spring.MyBatisSystemException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import dp.R;
import dp.util.JsonUtil;
import dp.util.ServletUtil;

public class ExceptionHandler implements HandlerExceptionResolver,Ordered {
	protected final Logger logger = LoggerFactory.getLogger(ExceptionHandler.class);

	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception ex) {
		R r = new R();
		r.setSuccess(false);
		if(ex instanceof IllegalArgumentException){
			r.setErrorMessage(ex.getMessage());
		}
		else if(ex instanceof DataAccessResourceFailureException){
			r.setErrorMessage("数据库连接错误，请联系管理员。");
		}
		else if(ex instanceof MyBatisSystemException || ex instanceof DataIntegrityViolationException){
			r.setErrorMessage("数据库操作失败，请联系管理员。");
		}
		else if(ex instanceof AppException){
			if(((AppException) ex).getErrorCode().equals("-1")) {
				String xReq = request.getHeader("x-requested-with");
				if (StringUtils.isNotBlank(xReq) && "XMLHttpRequest".equalsIgnoreCase(xReq)) {
					r.setErrorMessage(((AppException) ex).getErrorCode(), ex.getMessage());
				} else {
					return new ModelAndView("noAuthorize");
				}
			}else {
				r.setErrorMessage(((AppException) ex).getErrorCode(), ex.getMessage());
			}
		}
		else{
			r.setErrorMessage("程序异常，请联系管理员。");
		}
		ServletUtil.outputText(request, response, JsonUtil.toJSONString(r), ServletUtil.CONTENTTYPE_HTML, ServletUtil.CHARTSET_UTF8);
		return null;
	}

	@Override
	public int getOrder() {
		return Ordered.HIGHEST_PRECEDENCE;
	}

}
